package com.alogic.cert.bc.builder;

import com.alogic.cert.bc.KeyUsageTools;
import com.alogic.cert.bc.CertificateStoreImpl;
import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.KeyUsage;
import org.bouncycastle.cert.X509v3CertificateBuilder;

/**
 * 增加KeyUsage
 *
 * @since 1.6.13.40 [20210306 duanyy] <br>
 */
public class AddKeyUsage extends AbstractLogiclet {
    protected String pid = CertificateStoreImpl.XSCRIPT_OBJECT_ID;
    public static final String DEFAULT = "digitalSignature";
    protected String $usage = DEFAULT;
    protected String delimiter = ",";
    protected String $critical = "true";

    public AddKeyUsage(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);
        pid = PropertiesConstants.getString(p,"pid",pid,true);

        $usage = PropertiesConstants.getRaw(p,"usage",DEFAULT);
        $critical = PropertiesConstants.getRaw(p,"critical",$critical);
        delimiter = PropertiesConstants.getString(p,"delimiter",delimiter);
    }

    @Override
    protected void onExecute(XsObject root, XsObject current, final LogicletContext ctx, final ExecuteWatcher watcher){
        X509v3CertificateBuilder builder  = ctx.getObject(pid);
        if (builder != null){
            String [] usages = PropertiesConstants.transform(ctx,$usage,DEFAULT).split(delimiter);
            int usage = 0;
            for (String item:usages){
                if (StringUtils.isNotEmpty(item)){
                    Integer value = KeyUsageTools.getByName(item);
                    if (value != null){
                        usage += value.intValue();
                    }
                }
            }
            try {
                builder.addExtension(Extension.keyUsage, PropertiesConstants.transform(ctx,$critical,true), new KeyUsage(usage));
            }catch (Exception ex){
                log(ExceptionUtils.getStackTrace(ex));
            }
        }
    }
}
